package cn.ldw.test;

import java.util.ArrayList;
import java.util.List;

public class SpiralOrder {
    public static void main(String[] args) {
       int[][] matrix = new int[][]{{1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13, 14, 15, 16}};
        List<Integer> list = spiralOrder(matrix);
        for (Integer integer : list) {
            System.out.println(integer);
        }
    }
    public static List<Integer> spiralOrder(int[][] matrix) {
        int left = 0, right = matrix[0].length - 1;
        int top = 0, down = matrix.length - 1;
        List<Integer> ans = new ArrayList<>();
        while(true) {
            for(int i = left; i <= right; i++) {
                ans.add(matrix[top][i]);
            }
            top++;
            if(top > down) break;
            for(int i = top; i <= down; i++) {
                ans.add(matrix[i][right]);
            }
            right--;
            if(left > right) break;
            for(int i = right; i >= left; i--) {
                ans.add(matrix[down][i]);
            }
            down--;
            if(top > down) break;
            for(int i = down; i >= top; i--) {
                ans.add(matrix[i][left]);
            }
            left++;
            if(left > right) break;
        }
        return ans;
    }
}
